﻿// WebZHX.API/Middleware/RequestLoggingMiddleware.cs
using Infrastructure.Services;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;

namespace WebZHX.Middleware
{
    /// <summary>
    /// 请求日志中间件
    /// </summary>
    public class RequestLoggingMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestLoggingMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context, FileLoggerService loggerService)
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();

            try
            {
                await _next(context);
            }
            finally
            {
                stopwatch.Stop();

                // 记录请求日志到文件
                var userId = context.User?.FindFirst("sub")?.Value;
                var userName = context.User?.Identity?.Name;
                var ipAddress = context.Connection.RemoteIpAddress?.ToString();
                var userAgent = context.Request.Headers["User-Agent"].ToString();

                loggerService.LogApiRequest(
                    context.Request.Path,
                    context.Request.Method,
                    stopwatch.ElapsedMilliseconds,
                    userId,
                    userName,
                    ipAddress,
                    userAgent
                );
            }
        }
    }
}